import logging

from apps.model.serializeModel import model_to_list
from apps.settingApi.api.timerTask.model import timerTaskModel,timerTaskConfigModel
from apps.settingApi.api.timerTask.task import add_task, remove_task
from apps.settingApi.switchCase.serializeParameter import serializeGetFilter, pageResultData
from apps.settingApi.switchCase.settingCurd import getList as curdGetList
from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData

from comm.sqlalchemyConfig import db
timerTaskConfigViewModel = timerTaskConfigModel
timerTaskViewModel = timerTaskModel


def getList(args):
    serializeFilterList, args = serializeGetFilter(timerTaskViewModel)
    modelDataObj = timerTaskViewModel.query.filter(*serializeFilterList).order_by(
        timerTaskViewModel.order_type.asc(),timerTaskViewModel.sort.asc()).paginate(
        page=args['page'],
        per_page=args['pageSize'],
        error_out=False)
    objData = pageResultData(modelDataObj)
    result = model_to_list(modelDataObj, [])
    objData["data"] = result  # 分页数据
    return objData,None


def getPk(pk):
    return timerTaskViewModel.getPk(pk)


# 启动跟停止定时器
def controllerPostPk():
    task = db.session.query(timerTaskConfigModel).filter(timerTaskConfigModel.id == '2024053114505639250008110').first()
    if task!=None:
        if task.status==True:
            print("启动=======")

            jobId = add_task(trigger='interval',seconds=task.time)
            db.session.query(timerTaskConfigModel).filter().update(
                {"status": True,"process":jobId})

            db.session.commit()
        else:

            print("停止=======",task.process)
            remove_task(task.process)
            db.session.query(timerTaskConfigModel).filter().update(
                {"status": False, "process": ""})
            db.session.commit()
    else:
        timerTaskConfig = {}
        timerTaskConfig["id"] = '2024053114505639250008110'
        timerTaskConfig["time"] = 5
        timerTaskConfig["status"] = False
        timerTaskConfig["process"] = ""
        db.session.add(timerTaskConfigModel(**timerTaskConfig))
        db.session.commit()
